package com.wyf.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

/**
 * 实现WebApplicationInitializer 接口的类都可以在web应用启动程序是被加载
 */
public class WebInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        // 基于Java的配置类加载Spring的应用上下文
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        // 注册Mvc配置信息
        ctx.register(MvcConfig.class);
        // 设置ServletContext的上下文信息
        ctx.setServletContext(servletContext);
        // 配置转发器Dispatcher
        ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
        // 设置映射路径
        servlet.addMapping("/");
        // 启动实例化Bean
        servlet.setLoadOnStartup(1); // 值越小优先级越高
    }
}
